package com.jingmi.jingmiliving.commodity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingmi.jingmiliving.commodity.dao.AttrAttrgroupRelationDao;
import com.jingmi.jingmiliving.commodity.entity.AttrAttrgroupRelationEntity;
import com.jingmi.jingmiliving.commodity.entity.AttrEntity;
import com.jingmi.jingmiliving.commodity.service.AttrAttrgroupRelationService;
import com.jingmi.jingmiliving.commodity.service.AttrService;
import com.jingmi.jingmiliving.commodity.vo.AttrGroupWithAttrsVo;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingmi.common.utils.PageUtils;
import com.jingmi.common.utils.Query;

import com.jingmi.jingmiliving.commodity.dao.AttrgroupDao;
import com.jingmi.jingmiliving.commodity.entity.AttrgroupEntity;
import com.jingmi.jingmiliving.commodity.service.AttrgroupService;

import javax.annotation.Resource;


@Service("attrgroupService")
public class AttrgroupServiceImpl extends ServiceImpl<AttrgroupDao, AttrgroupEntity> implements AttrgroupService {
    @Resource
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Resource
    AttrService attrService;
    @Resource
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Override
    public PageUtils queryByAttrgroupId(Map<String, Object> params,Long attrGroupId) {
        System.out.println("one");
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.selectByGroupId(attrGroupId);
        ArrayList<Long> attrid = new ArrayList<>();
        System.out.println("two");
        for (AttrAttrgroupRelationEntity attrAttrgroupRelationEntity : attrAttrgroupRelationEntities) {
            Long attrId = attrAttrgroupRelationEntity.getAttrId();
            attrid.add(attrId);
        }
        System.out.println("three");
        List<AttrEntity> attrEntities = attrService.queryBaseByAttrIdPage(attrid);
        System.out.println("four");
        System.out.println("attrEntities==>"+attrEntities);
        System.out.println("params==>"+params);

        String stringCurrentPage = (String) params.get("page"); // 获取当前页码
        String stringPageSize = (String) params.get("limit"); // 获取每页记录数
        Integer currentPage= Integer.parseInt(stringCurrentPage);
        Integer pageSize= Integer.parseInt(stringPageSize);
        System.out.println("currentPage==>"+currentPage);
// 创建一个空的IPage对象
        System.out.println("five");
        IPage<AttrEntity> resultPage = new Page<>();

// 设置查询结果集合
        resultPage.setRecords(attrEntities);
        System.out.println("six");
// 设置总记录数和分页信息
        resultPage.setTotal(attrEntities.size()); // 设置总记录数
        resultPage.setSize(pageSize); // 设置每页记录数
        resultPage.setCurrent(currentPage);
        System.out.println("seven");
        return new PageUtils(resultPage);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        System.out.println("params=====>" +params);
        IPage<AttrgroupEntity> page = this.page(
                new Query<AttrgroupEntity>().getPage(params),
                new QueryWrapper<AttrgroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId) {
        System.out.println("重载方法被执行===============================");
        System.out.println("params==>"+params+"cateGortId===>"+categoryId);
        QueryWrapper<AttrgroupEntity> wrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        //查询条件 //params不为空
        if (StringUtils.isNotBlank(key)){
            /*意思就是wrapper是一个QueryWrapper
            他有一个and方法接受一个QueryWrapper
            这个queryWrapper用Lambda表达式表现
            wrapper 是一个 QueryWrapper 对象，
            它提供了各种查询条件构造方法，以便我们可以方便地构建查询条件。其中，and
            方法用于添加一个 AND 连接符，并返回一个新的 QueryWrapper 对象供下一次链式调用使用。
            在这里，我们使用 Lambda 表达式来作为 and 方法的参数，具体形式是
            (obj) -> { obj.eq("id", key).or().like("name", key); }。
            这里的 (obj) 是 Lambda 表达式的形参，表示传入的参数类型为 QueryWrapper。
            而 { obj.eq("id", key).or().like("name", key); }
            则是 Lambda 表达式的方法体，它调用 QueryWrapper 对象的 eq、or 和 like 方法，
            实现了按照 id 等于 key 或者 name 包含 key 的条件进行查询。在这种情况下，
            我们可以将 Lambda 表达式看作一个函数，它接受一个 QueryWrapper 对象作为参数，
            并返回一个没有明确类型的结果（因为在这个例子中并没有通过 Lambda 表达式返回任何值）。
            当我们向 and 方法传递一个 Lambda 表达式时，它会将这个 Lambda 表达式封装成一个函数式接口，
            然后将这个函数式接口作为参数传递给 and 方法。*/
            //wrapper.eq("id", key).or().like("name", key);
              wrapper.and((obj)->{
                  obj.eq("id", key).or().like("name", key);
              });
        }
        if (categoryId==0){
            //没带categoryId
            IPage<AttrgroupEntity> page = this.page(new Query<AttrgroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        }else {
            //带categoryId
            wrapper.eq("category_id",categoryId);
            IPage<AttrgroupEntity> page = this.page(
                    new Query<AttrgroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }

    }

    @Override
    public void deleteBatches(AttrAttrgroupRelationEntity[] attrAttrgroupRelationEntities) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(attrAttrgroupRelationEntities);
        attrAttrgroupRelationDao.deleteBatches(entities);
    }

    @Override
    public PageUtils queryBaseAttrOptional(Map<String, Object> params, Long attrGroupId) {
        AttrgroupEntity byId = this.getById(attrGroupId);
        Long categoryId = byId.getCategoryId();
        //List<AttrEntity> attrEntities = attrService.queryBaseAttrPageByCategoryId(categoryId);
        String key = (String)params.get("key");
        //查询条件 //params不为空
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)){
            attrEntityQueryWrapper.and((obj)->{
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        //找出category下的属性组
        List<AttrgroupEntity> queryByCategoryId = this.list(new QueryWrapper<AttrgroupEntity>().eq("category_id", categoryId));
        List<Long> StreamOutattrGroupId = queryByCategoryId.stream().map((item -> {
            return item.getId();
        })).collect(Collectors.toList());
        //找出属性组下的绑定过的attr_id
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntitylist = attrAttrgroupRelationService.list(
                new QueryWrapper<AttrAttrgroupRelationEntity>().
                        in("attr_group_id", StreamOutattrGroupId));
        List<Long> attrId = attrAttrgroupRelationEntitylist.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        if (attrId!=null&&attrId.size()!=0){
            attrEntityQueryWrapper.notIn("attr_id",attrId);
        }
        //List<AttrEntity> list = attrService.list(attrEntityQueryWrapper);


        /*IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper);*/
        IPage<AttrEntity> page =attrService.page( new Query<AttrEntity>().getPage(params),attrEntityQueryWrapper);
        System.out.println("page==>"+page);
        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupWithAttrsVo> addAttrGroupWithAttrsVo(Long categoryId) {
        List<AttrgroupEntity> categoryId1 = this.list(new QueryWrapper<AttrgroupEntity>().eq("category_id", categoryId));
        List<AttrGroupWithAttrsVo> attrGroupId = categoryId1.stream().map(item -> {
            AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
            //设置基本属性组
            BeanUtils.copyProperties(item, attrGroupWithAttrsVo);
            Long id = item.getId();
            List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.list(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", id));

            //收集基本属性组下的基本属性
            List<AttrEntity> collect = list.stream().map(obj -> {
                Long attrId = obj.getAttrId();
                AttrEntity byId = attrService.getById(attrId);
                return byId;
            }).collect(Collectors.toList());

            attrGroupWithAttrsVo.setAttrs(collect);
            return attrGroupWithAttrsVo;
        }).collect(Collectors.toList());


        return attrGroupId;
    }

}